<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>人员管理</el-breadcrumb-item>
      <el-breadcrumb-item>维修员</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入姓名"
            v-model="queryInfo.repairmanName"
            clearable
            @clear="getrepairmanList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getrepairmanList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog()"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格数据区域 -->
      <el-table :data="repairmanList" stripe border>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="repairmanId" label="编号"> </el-table-column>
        <el-table-column prop="repairmanName" label="姓名"> </el-table-column>
        <el-table-column prop="repairmanTel" label="电话"> </el-table-column>
        <el-table-column prop="repairmanAddress" label="地址">
        </el-table-column>
        <el-table-column prop="repairmanRepairtype" label="维修类型">
        </el-table-column>
        <el-table-column width="180px" prop="address" label="操作">
          <template slot-scope="scope">
            <!-- 编辑用户 -->
            <el-button
              :disabled="flag"
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.repairmanId)"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              :disabled="flag"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.repairmanId)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[2, 3, 6, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDalogClose"
    >
      <!-- 主体 -->
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="90px"
      >
        <el-form-item label="用户姓名" prop="repairmanName">
          <el-input v-model="addForm.repairmanName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="repairmanPassword">
          <el-input v-model="addForm.repairmanPassword"></el-input>
        </el-form-item>

        <el-form-item label="维修类型">
          <el-select
            style="width: 100%"
            v-model="addForm.repairmanRepairtype"
            placeholder="请选择维修类型"
          >
            <el-option
              v-for="(type, index) in alltype"
              :key="index"
              :label="type"
              :value="type"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="联系地址" prop="repairmanAddress">
          <el-input v-model="addForm.repairmanAddress"></el-input>
        </el-form-item>
        <el-form-item label="用户电话" prop="repairmanTel">
          <el-input v-model="addForm.repairmanTel"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 主体 -->
      <el-form
        ref="editFormRef"
        :rules="addFormRules"
        :model="editForm"
        label-width="90px"
      >
        <el-form-item label="用户编号">
          <el-input disabled v-model="editForm.repairmanId"></el-input>
        </el-form-item>

        <el-form-item label="用户姓名" prop="repairmanName">
          <el-input v-model="editForm.repairmanName"></el-input>
        </el-form-item>

        <el-form-item label="维修类型">
          <el-select
            style="width: 100%"
            v-model="editForm.repairmanRepairtype"
            placeholder="请选择维修类型"
          >
            <el-option
              v-for="(type, index) in alltype"
              :key="index"
              :label="type"
              :value="type"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="联系地址" prop="repairmanAddress">
          <el-input v-model="editForm.repairmanAddress"></el-input>
        </el-form-item>
        <el-form-item label="用户电话" prop="repairmanTel">
          <el-input v-model="editForm.repairmanTel"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 底部 -->
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    // var checkEmail = (rule, value, cb) => {
    //   const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    //   if (regEmail.test(value)) {
    //     return cb();
    //   }
    //   cb(new Error("请输入合法的邮箱"));
    // };
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3|4|5|7|8][0-9]{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      queryInfo: {
        repairmanName: "",
        pageNum: 1,
        pageSize: 6,
      },
      repairmanList: [],
      total: 0,
      // 控制添加用户对话框的隐藏与开启
      dialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        repairmanName: "",
        repairmanPassword: "123456",
        repairmanTel: "",
        repairmanAddress: "",
        repairmanRepairtype: "",
      },
      // 添加用户表单的验证规则
      addFormRules: {
        repairmanName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        repairmanPassword: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        repairmanTel: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        repairmanAddress: [
          { required: true, message: "请输入地址", trigger: "blur" },
        ],
        repairmanRepairtype: [
          { required: true, message: "请选择维修类型", trigger: "blur" },
        ],
      },
      // 编辑用户对话框状态
      editDialogVisible: false,
      // 根据id获取到的信息
      editForm: {},
      // 角色列表
      rolesList: [],
      roleId: "",
      alltype: [],
      flag: true,
    };
  },
  methods: {
    async getrepairmanList() {
      const { data: res } = await this.$http.get("getAllRepairman", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("请求用户数据失败");
      }
      this.repairmanList = res.data.records;
      this.total = res.data.total;
    },
    // 页大小的变化
    handleSizeChange(newsize) {
      this.queryInfo.pageSize = newsize;
      this.getrepairmanList();
    },
    // 页面值的变化
    handleCurrentChange(newPagenum) {
      this.queryInfo.pageNum = newPagenum;
      this.getrepairmanList();
    },
    // 修改用户状态
    async userStateChanged(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      console.log(row.id);
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        return this.$message.error(res.meta.msg);
      }
      this.$message.success("状态更新成功");
    },
    // 添加用户对话框关闭前清空
    addDalogClose() {
      this.$refs.addFormRef.resetFields();
      this.addForm.repairmanRepairtype = "";
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return false;
        // 添加用户请求
        const { data: res } = await this.$http.post(
          "addRepairman",
          this.addForm
        );
        if (res.meta.status !== 200) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.dialogVisible = false;
        this.getrepairmanList();
      });
    },
    // 编辑用户的数据初始化
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("getRepairmanById/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("请求用户信息失败");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    async deleteUser(id) {
      // 删除操作前的验证
      const confirmReturn = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // 点击确认返回confirm字符串
      if (confirmReturn !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        "deleteRepairmanById/" + id
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      this.getrepairmanList();
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false;
        // 发起修改用户的数据请求
        const { data: res } = await this.$http.put(
          "editRepairmanById/" + this.editForm.repairmanId,
          {
            repairmanName: this.editForm.repairmanName,
            repairmanTel: this.editForm.repairmanTel,
            repairmanAddress: this.editForm.repairmanAddress,
            repairmanRepairtype: this.editForm.repairmanRepairtype,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("数据修改失败");
        this.editDialogVisible = false;
        this.getrepairmanList();
        this.$message.success("数据修改成功");
      });
    },

    //获取维修类型
    async getAllRepairmanType() {
      const { data: res } = await this.$http.get("getAllRepairmanType");
      if (res.meta.status !== 200) {
        return this.$message.error("获取信息失败，请联系有关人员");
      }
      this.alltype = res.data;
    },
    showAddDialog() {
      if (this.flag) {
        return this.$message.error("你没有该权限");
      }
      this.dialogVisible = true;
    },
  },
  created() {
    this.getAllRepairmanType();
    this.getrepairmanList();
    this.flag =
      JSON.parse(sessionStorage.getItem("user")).identity !== "管理员";
  },
};
</script>

<style></style>
